<template>
    <el-form ref="form" :rules="rules" :model="form" label-width="110px" class="ship-edayun-warp">
        <el-row :gutter="20">
            <el-col :span="6">
                <el-input
                    type="textarea"
                    :autosize="{ minRows: 15, maxRows: 20 }"
                    :placeholder="$t('m.placeholder.pleaseEnteContent')"
                    v-model="textarea"
                    @blur="findtextarea"
                ></el-input>
                <el-input
                    style="margin-top: 15px;"
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                    :placeholder="$t('m.label.remarks')"
                    v-model="form.remarks"
                    size="medium"
                ></el-input>
            </el-col>
            <el-col :span="18">
                <el-row>
                    <el-col :span="10">
                        <el-form-item :label="$t('m.label.founder')" prop="creater">
                            <el-input v-model="form.creater" size="medium" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="Order ID" prop="fulfillmentOrderId">
                            <el-input v-model="form.fulfillmentOrderId" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.clientSName')" prop="name">
                            <el-input v-model="form.name" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.address') + '1'" prop="addressLine1">
                            <el-input v-model="form.addressLine1" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.address') + '2'" prop="addressLine2">
                            <el-input v-model="form.addressLine2" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.districtCity')" prop="city">
                            <el-input v-model="form.city" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.state')" prop="stateProvinceCode">
                            <el-input v-model="form.stateProvinceCode" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.postalCode')" prop="postalCode">
                            <el-input v-model="form.postalCode" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.country')" prop="countryCode">
                            <el-select
                                v-model="form.countryCode"
                                filterable
                                :placeholder="$t('m.placeholder.selectCountry')"
                                size="medium"
                            >
                                <el-option
                                    :label="item.countryName"
                                    :value="item.alpha2"
                                    :key="item.alpha2"
                                    v-for="item in country"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.phone')" prop="phoneNumber">
                            <el-input v-model="form.phoneNumber" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.Within3months')" prop="within3months">
                            <el-radio
                                v-model="form.within3months"
                                :label="true"
                            >{{$t('m.label.Yes')}}</el-radio>
                            <el-radio
                                v-model="form.within3months"
                                :label="false"
                            >{{$t('m.label.no')}}</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="2">
                        <el-form-item :label="$t('m.label.lasertCode')" prop="productCode">
                            <el-input v-model="form.productCode" size="medium"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.qualityProblem')" prop="returnReasonId">
                            <el-select
                                v-model="form.returnReasonId"
                                filterable
                                :placeholder="$t('m.placeholder.selectqualityProblem')"
                                clearable
                                size="medium"
                            >
                                <el-option
                                    v-for="item in returnReasonList"
                                    :label="item.reason"
                                    :value="item.returnReasonId"
                                    :key="item.returnReasonId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item
                            :label="$t('m.label.fulfillmentReason')"
                            prop="fulfillmentReasonId"
                        >
                            <el-select
                                v-model="form.fulfillmentReasonId"
                                filterable
                                :placeholder="$t('m.placeholder.selectfulfillmentReason')"
                                clearable
                                size="medium"
                            >
                                <el-option
                                    v-for="item in fulfllmentReasonList"
                                    :label="item.fulfillmentReason"
                                    :value="item.fulfillmentReasonId"
                                    :key="item.fulfillmentReasonId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.BU')" prop="businessUnitId">
                            <BU
                                :form="form"
                                formId="businessUnitId"
                                addSize="mini"
                                size="small"
                            ></BU>
                        </el-form-item>
                        <el-form-item :label="$t('m.label.shippingWarehouse')" prop="warehouseId">
                            <el-select
                                v-model="form.warehouseId"
                                @change="edaYunAsinSkuIds"
                                filterable
                                :placeholder="$t('m.placeholder.selectShippingWarehouse')"
                                size="medium"
                            >
                                <el-option
                                    v-for="item in allEdaYunWarehouse"
                                    :label="item.warehouseName"
                                    :value="item.warehouseId"
                                    :key="item.warehouseId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item
                            :label="$t('m.label.shippinglogistics')"
                            prop="courierAccountId"
                        >
                            <el-select
                                v-model="form.courierAccountId"
                                :placeholder="$t('m.placeholder.selectShippinglogistics')"
                                size="medium"
                                filterable
                            >
                                <el-option
                                    v-for="item in allCourier"
                                    :label="item.courierAccountName"
                                    :value="item.courierAccountId"
                                    :key="item.key"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <div v-loading="loading" style="min-height: 50px;">
                            <div class="form-item-box" v-if="edaYunAsinSku.length > 0">
                                <el-form-item
                                    label-width="0"
                                    v-for="(item, index) in edaYunAsinSku"
                                    :key="index"
                                >
                                    <div class="ASIN">ASIN:{{ item.ASIN }}</div>
                                    <div class="quantity">QTY:{{ item.QTY }}</div>
                                    <div
                                        v-for="items in item.data"
                                        :key="items.edaYunSkuId"
                                        class="items"
                                    >
                                        <el-radio
                                            v-model="edaYunAsinSkuID[index]"
                                            :label="items.edaYunSku"
                                            @change="edaYunAsinSkuIds"
                                        >{{ items.edaYunSku }}{{ items.edaYunSku }}{{ items.edaYunSku }}</el-radio>
                                        <div
                                            class="inventory"
                                        >{{$t('m.label.InStock')}}：{{ items.inventory }}</div>
                                    </div>
                                </el-form-item>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button
                        type="primary"
                        icon="el-icon-circle-plus-outline"
                        size="medium"
                        @click="submitForm('form')"
                    >{{$t('m.button.createShipment')}}</el-button>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>
<script>
const ERR_OK = 200;
import BU from "components/searchfor/bu";
export default {
    data() {
        return {
            loading: false,
            textarea: "",
            form: {
                addressLine1: "",
                addressLine2: "",
                businessUnitId: "",
                city: "",
                countryCode: "",
                courierAccountId: "",
                creater: this.$store.getters.userName,
                fulfillmentOrderId: "",
                fulfillmentReasonId: "",
                name: "",
                orderItemList: [],
                phoneNumber: "",
                postalCode: "",
                productCode: "",
                returnReasonId: "",
                stateProvinceCode: "",
                warehouseId: "",
                within3months: true
            },
            country: [],
            fulfllmentReasonList: [],
            returnReasonList: [],
            allCourier: [],
            allEdaYunWarehouse: [],
            edaYunAsinSku: [],
            edaYunAsinSkuID: [],
            rules: {
                creater: [
                    { required: true, message: "请填写创建人", trigger: "blur" }
                ],
                fulfillmentOrderId: [
                    {
                        required: true,
                        message: this.$t("m.placeholder.pleaseEnteOrderID"),
                        trigger: "blur"
                    }
                ],
                name: [
                    {
                        required: true,
                        message: this.$t("m.placeholder.pleaseEnteclientsname"),
                        trigger: "blur"
                    }
                ],
                addressLine1: [
                    {
                        required: true,
                        message: this.$t("m.placeholder.pleaseEnteAddress1"),
                        trigger: "blur"
                    }
                ],
                city: [
                    {
                        required: true,
                        message: this.$t(
                            "m.placeholder.pleaseEnteDistrictCity"
                        ),
                        trigger: "blur"
                    }
                ],
                postalCode: [
                    {
                        required: true,
                        message: this.$t("m.placeholder.pleaseEnteZipCode"),
                        trigger: "blur"
                    }
                ],
                countryCode: [
                    {
                        required: true,
                        message: this.$t("m.placeholder.selectCountry"),
                        trigger: "change"
                    }
                ],
                warehouseId: [
                    {
                        required: true,
                        message: this.$t(
                            "m.placeholder.selectShippingWarehouse"
                        ),
                        trigger: "change"
                    }
                ],
                courierAccountId: [
                    {
                        required: true,
                        message: this.$t(
                            "m.placeholder.selectShippinglogistics"
                        ),
                        trigger: "change"
                    }
                ]
            },
            SkuAndWarehouse: []
        };
    },
    activated() {
        // if(JSON.stringify(this.$route.params) !== "{}"){
        //   console.log(this.$route.params,"----")
        //   this.form.fulfillmentOrderId = this.$route.params.amzOrderId
        //   this.form.fulfillmentOrderId = this.$route.params.amzOrderId
        // }
    },
    created() {
        this.getcountry();
        this.getfulfllmentReasonList();
        this.getReturnReasonList();
        this.getAllCourier();
        this.getAllEdaYunWarehouse();
    },
    mounted() {},
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.form.orderItemList.length == 0) {
                        this.$message.warning(this.$t("m.message.ASINinvalid"));
                    } else if (
                        this.SkuAndWarehouse.indexOf(false) === -1
                            ? false
                            : true
                    ) {
                        this.$message.warning(
                            this.$t("m.message.messageAvailableStock")
                        );
                    } else {
                        this.$ajax({
                            method: "post",
                            url:
                                this.GLOBAL.fulfillmentOrderService +
                                "/fulfillmentOrder/createFulfillmentOrder",
                            data: this.form
                        }).then(res => {
                            if (res.data.code === ERR_OK) {
                                this.$message.success(
                                    this.$t("m.message.createdSuccessfully")
                                );
                                this.$emit('close')
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        });
                    }
                } else {
                    return false;
                }
            });
        },
        //获取国家
        getcountry() {
            this.$ajax(
                this.GLOBAL.fulfillmentOrderService + "/country/findAll"
            ).then(res => {
                if (res.data.code === ERR_OK) {
                    this.country = res.data.data;
                }
            });
        },
        //国家赋值
        taskCountry() {
            let countryID;
            if (this.customizeGB(this.form.countryCode)) {
                countryID = "GB";
            } else if (this.customizeUS(this.form.countryCode)) {
                countryID = "US";
            } else if (this.customizeDE(this.form.countryCode)) {
                countryID = "DE";
            } else if (this.customizeFR(this.form.countryCode)) {
                countryID = "FR";
            } else if (this.customizeIT(this.form.countryCode)) {
                countryID = "IT";
            } else if (this.customizeES(this.form.countryCode)) {
                countryID = "ES";
            } else if (this.customizeCA(this.form.countryCode)) {
                countryID = "CA";
            } else {
                for (var i = 0; i < this.country.length; i++) {
                    if (this.country[i].countryName === this.form.countryCode) {
                        countryID = this.country[i].alpha2;
                        break;
                    } else {
                        countryID = "";
                    }
                }
            }
            this.form.countryCode = countryID;
        },
        //自定义选择国家
        //英国
        customizeGB(id) {
            let data = ["UK", "Uk", "ENGLAND", "UNITED KINGDOM"];
            return data.indexOf(id.toUpperCase()) === -1 ? false : true;
        },
        //美国
        customizeUS(id) {
            let data = [
                "USA",
                "UNITED STATES",
                "US",
                "UNITED STATES OF AMERICA",
                "AMERICA"
            ];
            return data.indexOf(id.toUpperCase()) === -1 ? false : true;
        },
        //德国
        customizeDE(id) {
            let data = ["DE", "GERMANY"];
            return data.indexOf(id.toUpperCase()) === -1 ? false : true;
        },
        //法国
        customizeFR(id) {
            let data = ["FR", "FRANCE"];
            return data.indexOf(id.toUpperCase()) === -1 ? false : true;
        },
        //意大利
        customizeIT(id) {
            let data = ["IT", "ITALY", "ITALIA"];
            return data.indexOf(id.toUpperCase()) === -1 ? false : true;
        },
        //西班牙
        customizeES(id) {
            let data = ["ES", "SPAIN"];
            return data.indexOf(id.toUpperCase()) === -1 ? false : true;
        },
        //加拿大
        customizeCA(id) {
            let data = ["CA", "CANADA"];
            return data.indexOf(id.toUpperCase()) === -1 ? false : true;
        },
        //获取发货原因
        getfulfllmentReasonList() {
            this.$ajax(
                this.GLOBAL.fulfillmentOrderService +
                    "/fulfllmentReason/getfulfllmentReasonList"
            ).then(res => {
                if (res.data.code === ERR_OK) {
                    this.fulfllmentReasonList = res.data.data;
                }
            });
        },
        //品质原因
        getReturnReasonList() {
            this.$ajax(
                this.GLOBAL.fulfillmentOrderService +
                    "/fulfillmentReturnReason/getReturnReasonList"
            ).then(res => {
                if (res.data.code === ERR_OK) {
                    this.returnReasonList = res.data.data;
                }
            });
        },
        // 获取物流
        getAllCourier() {
            this.$ajax
                .get(
                    this.GLOBAL.fulfillmentOrderService +
                        "/edaYunWarehouse/getAllCourier"
                )
                .then(res => {
                    if (res.data.code === ERR_OK) {
                        this.allCourier = res.data.data;
                    }
                });
        },
        // 获取仓库
        getAllEdaYunWarehouse() {
            this.$ajax
                .get(
                    this.GLOBAL.fulfillmentOrderService +
                        "/edaYunWarehouse/getAllEdaYunWarehouse"
                )
                .then(res => {
                    if (res.data.code === ERR_OK) {
                        this.allEdaYunWarehouse = res.data.data;
                    }
                });
        },
        //asin查找sku
        getedaYunAsinSku(val) {
            let asin;
            for (let i in val.asin) {
                if (val.asin[i]) {
                    asin = val.asin[i].replace('"', "");
                }
                this.loading = true;
                this.$ajax
                    .get(
                        this.GLOBAL.fulfillmentOrderService +
                            "/edaYunAsinSku/selectEdaYunSkuByAsin?asin=" +
                            asin
                    )
                    .then(res => {
                        if (
                            res.data.code === ERR_OK &&
                            res.data.data.length > 0
                        ) {
                            let data = res.data.data;
                            data.forEach(item => {
                                item.inventory = "";
                            });
                            this.edaYunAsinSku.push({
                                data: data,
                                ASIN: val.asin[i].replace('"', ""),
                                QTY: val.aty[i].replace('"', ""),
                                fulfillmentOrderId: val.id
                            });
                        } else {
                            this.$message.warning(
                                this.$t("m.message.didNotFindSKU")
                            );
                        }
                        this.loading = false;
                    });
            }
        },
        // 给form.orderItemList赋值
        edaYunAsinSkuIds() {
            this.form.orderItemList = [];
            this.SkuAndWarehouse = [];
            this.edaYunAsinSkuID.forEach((item, index) => {
                if (this.edaYunAsinSku[index]) {
                    this.form.orderItemList.push({
                        sellerSku: item,
                        asin: this.edaYunAsinSku[index].ASIN,
                        quantity: this.edaYunAsinSku[index].QTY,
                        fulfillmentOrderId: this.edaYunAsinSku[index]
                            .fulfillmentOrderId
                    });
                    this.getqueryInventoryBySkuAndWarehouseId(
                        item,
                        this.edaYunAsinSku[index].QTY,
                        index
                    );
                }
            });
        },
        //sku查看仓库库存
        getqueryInventoryBySkuAndWarehouseId(sku, QTY, index) {
            this.$ajax
                .get(
                    this.GLOBAL.fulfillmentOrderService +
                        "/fulfillmentOrder/queryInventoryBySkuAndWarehouseId?sku=" +
                        sku +
                        "&warehouseId=" +
                        this.form.warehouseId
                )
                .then(res => {
                    if (res.data.code === ERR_OK) {
                        this.edaYunAsinSku[index].data.forEach(items => {
                            if (items.edaYunSku === sku) {
                                items.inventory = res.data.data;
                            }
                        });
                        this.SkuAndWarehouse.push(
                            res.data.data < QTY ? false : true
                        );
                    }
                });
        },
        findtextarea() {
            this.edaYunAsinSku = [];
            let item = this.textarea.trim().split("\t");
            if (item.length >= 5) {
                item[4].split("\n").forEach((el, i) => {
                    if (el) {
                        if (i === 0) {
                            this.form.name = el.replace('"', ""); //客户名称
                        } else if (i === 1) {
                            this.form.addressLine1 = el; //地址1
                        } else if (i === 2) {
                            this.form.addressLine2 = el; //地址2
                        } else if (i === 3) {
                            this.form.city = el; //区/市
                        } else if (i === 4) {
                            this.form.stateProvinceCode = el; //州
                        } else if (i === 5) {
                            this.form.postalCode = el; //编码
                        } else if (i === 6) {
                            this.form.countryCode = el.replace('"', ""); //国家
                        }
                    }
                });
                this.form.fulfillmentOrderId = item[0]
                    .replace(/\"/g, "")
                    .replace(/\'/g, "")
                    .trim(); //订单号
                this.form.productCode = item[2]; //镭射编码
                let items = {
                    id: this.form.fulfillmentOrderId,
                    asin: item[1].split(/[(\r\n)\r\n]+/),
                    aty: item[3].split(/[(\r\n)\r\n]+/)
                };
                this.getedaYunAsinSku(items);
                this.taskCountry();
            } else {
                this.$message.warning(this.$t("m.message.messageRecopy"));
            }
        }
    },
    watch: {
        //默认选中sku
        edaYunAsinSku(val) {
            if (this.edaYunAsinSku.length > 0) {
                val.forEach((el, i) => {
                    el.data.forEach((item, is) => {
                        if (is === 0) {
                            this.edaYunAsinSkuID[i] = item.edaYunSku;
                        }
                    });
                });
                this.edaYunAsinSkuIds();
            }
        },
        //国家变动自定义给仓库物流绑定值
        "form.countryCode"(val) {
            switch (val) {
                case "GB":
                    this.form.warehouseId = 51;
                    this.form.courierAccountId = 100;
                    break;
                case "US":
                    this.form.warehouseId = 7;
                    this.form.courierAccountId = 80;
                    break;
                case "DE":
                    this.form.warehouseId = 34;
                    this.form.courierAccountId = 105;
                    break;
                case "FR":
                    this.form.warehouseId = 34;
                    this.form.courierAccountId = 102;
                    break;
                case "IT":
                    this.form.warehouseId = 34;
                    this.form.courierAccountId = 102;
                    break;
                case "ES":
                    this.form.warehouseId = 34;
                    this.form.courierAccountId = 102;
                    break;
                case "PL":
                    this.form.warehouseId = 34;
                    this.form.courierAccountId = 102;
                    break;
                case "AT":
                    this.form.warehouseId = 34;
                    this.form.courierAccountId = 102;
                    break;
                default:
                    this.form.warehouseId = "";
                    this.form.courierAccountId = "";
            }
        }
    },
    components:{
        BU
    }
};
</script>
<style lang="stylus" scoped>
.form-item-box {
    margin: 15px 0 15px 15px;
    padding: 10px 15px;
    border: 1px solid #d2d5da;
    background: #ebeef5;

    .ASIN, .quantity {
        display: inline-block;
    }

    .quantity {
        padding-left: 20px;
    }

    .el-radio {
        white-space: nowrap;
        text-overflow: ellipsis;
        display: inline-block;
        max-width: 150px;
        overflow: hidden;
        margin: 0;
        margin-top: 8px;
    }

    .items {
        height: 30px;
        line-height: 30px;
    }

    .inventory {
        float: right;
        width: 80px;
    }
}

.el-form-item {
    margin-bottom: 5px;
}

.el-button {
    float: right;
}
</style>
<style>
.ship-edayun-warp .el-form-item__error {
    position: relative;
}
</style>
   